/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author 52461
 */
public class MC_600 {

    private String baseData;
    private String device_code = "MC-600";
    private String code = "LA";
    private String sampletype = "全血";
    private String sampletypeId = null;

    public MC_600(String baseData) {
        this.baseData = baseData;
        // getSampleTypeId();
        parseComData();

    }

    public void getSampleTypeId() {
        try {
            sampletypeId = Db.findFirst("select * from lis_sampletype where SAMPLEDESCRIBE='" + sampletype + "'").get("PK") + "";

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void parseComData() {
        try {
            String sampleNo = null;
            String testDate = null;

            Map<String, String> resultMap = new HashMap<String, String>();
            Document document = DocumentHelper.parseText(baseData);
            //获取根节点元素对象
            Element node = document.getRootElement();

            Element smpinfo = node.element("smpinfo");

            Iterator<Element> it = smpinfo.elementIterator();
            // 遍历

            while (it.hasNext()) {
                // 获取某个子节点对象
                Element e = it.next();
                Element n = e.element("n");
                Element v = e.element("v");
                if (n.getText() != null && n.getText().equalsIgnoreCase("ID")) {
                    sampleNo = v.getText();
                } else if (n.getText() != null && n.getText().equalsIgnoreCase("DATE")) {
                    testDate = v.getText();
                }

            }
            Element smpresults = node.element("smpresults");
            Iterator<Element> result = smpresults.elementIterator();
            // 遍历

            while (result.hasNext()) {
                // 获取某个子节点对象
                Element e = result.next();
                //获取结果数据
                if (e.getName().equalsIgnoreCase("p")) {
                    Element n = e.element("n");
                    Element v = e.element("v");
                    resultMap.put(n.getText(), v.getText());
                    //System.out.println(n.getText() + ":" + v.getText());
                } // 获取直方图数据
                else if (e.getName().equalsIgnoreCase("hgrams")) {
                    Iterator<Element> items = e.elementIterator();
                    while (items.hasNext()) {
                        Element hgram = items.next();
                        Element n = hgram.element("n");
                        Element hgdata = hgram.element("hgdata");
                        Element v = hgdata.element("v");
                        if (n.getText().equalsIgnoreCase("DIFF")) {
                            resultMap.put("image#" + n.getText(), parseDiff(v.getText()));

                        } else {
                            resultMap.put("image#" + n.getText(), v.getText());
                            // System.out.println(n.getText()+":"+v.getText());
                        }
                    }

                }

            }
            sendDb(Tool.getSampleNo(code, sampleNo), testDate, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }
    }

    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
        // System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库");
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();
            //System.out.println("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "' and SAMPLETYPE= '"+sampletypeId+"'");
            Record rs = Db.findFirst("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "'");
            if (rs != null) {
                newMap.put("ITEMPK", rs.get("PK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);
                System.out.println(rs.getStr("TESTID"));
                if (rs.getStr("TESTID").equalsIgnoreCase("image#WBC") || rs.getStr("TESTID").equalsIgnoreCase("image#RBC") || rs.getStr("TESTID").equalsIgnoreCase("image#PLT")) {
                    newMap.put("RESULTFLAG", "1");
                    // System.out.println("yyyyyyyyyy-----------------------");
                }
               else if (rs.getStr("TESTID").equalsIgnoreCase("image#DIFF")) {
                    newMap.put("RESULTFLAG", "3");
                    // System.out.println("yyyyyyyyyy-----------------------");
                } else {
                    newMap.put("RESULTFLAG", "0");
                }
                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            System.out.println(e);
        }
        return true;

    }

    private String parseDiff(String str) {

        char s[] = str.toCharArray();
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < s.length; i++) {
            if (s[i] != '0') {
                list.add(i % 128 + " " + Integer.parseInt((i / 128) + ""));
            }
        }
        return list.toString().replace("[", "").replace("]", "");
    }

}
